package com.hzy.alibaba.config;

import com.mysql.cj.jdbc.MysqlXADataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @Author:dyz Date:9:34 2019/8/5
 */

/**
 * 数据源的配置
 */
@Configuration
public class DataSourcesConfig {

    /**
     * 链接数据库配置 -- 主数据源
     * @return
     * @throws SQLException
     */
    @ConfigurationProperties(prefix = "spring.primary.datasource")
    @Bean(name = "primaryMysqlXADataSource")
    public MysqlXADataSource getPrimaryMysqlXADataSource() throws SQLException{
        // 新建数据源，并将数据源配置信息装置
        MysqlXADataSource mysqlXADataSource = new MysqlXADataSource();
        mysqlXADataSource.setPinGlobalTxToPhysicalConnection(true);
        return mysqlXADataSource;
    }

    /**
     * 配置数据源 -- 主数据源
     * @param primaryMysqlXADataSource
     * @return
     * @throws SQLException
     */
    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @Primary
    public DataSource primaryDataSource(MysqlXADataSource primaryMysqlXADataSource) throws SQLException {
        // 将事物信息交给atomikos进行统一管理
        AtomikosDataSourceBean xDataSource = new AtomikosDataSourceBean();
        // 将数据源信息放入到atomikos容器中
        xDataSource.setXaDataSource(primaryMysqlXADataSource);
        xDataSource.setUniqueResourceName("primaryDataSource");
        return xDataSource;
    }

    /**
     * 链接数据库配置 -- 次数据源
     * @return
     * @throws SQLException
     */
    @ConfigurationProperties(prefix = "spring.secondary.datasource")
    @Bean(name = "secondaryMysqlXADataSource")
    public MysqlXADataSource getSecondaryMysqlXADataSource() throws SQLException{
        // 新建数据源，并将数据源配置信息装置
        MysqlXADataSource mysqlXADataSource = new MysqlXADataSource();
        mysqlXADataSource.setPinGlobalTxToPhysicalConnection(true);
        return mysqlXADataSource;
    }

    /**
     * 配置数据源 -- 次数据源
     * @param secondaryMysqlXADataSource
     * @return
     * @throws SQLException
     */
    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    public DataSource secondaryDataSource(MysqlXADataSource secondaryMysqlXADataSource) throws SQLException {
        // 将事物信息交给atomikos进行统一管理
        AtomikosDataSourceBean xDataSource = new AtomikosDataSourceBean();
        // 将数据源信息放入到atomikos容器中
        xDataSource.setXaDataSource(secondaryMysqlXADataSource);
        xDataSource.setUniqueResourceName("secondaryDataSource");
        return xDataSource;
    }
}

